<?php
namespace app\api\model;

use think\Db;

class TakeoutModel  
{
    /**
     * 单例模式
     * @return TakeoutModel
     *
     */
    public static function instance(){
        static $m = null;
        if(!$m){
            $m = new TakeoutModel();
        }
        return $m;
    }
    /**
     * 提现
     */
    public function MoneySubmit($data,$uid){
        $uidmoney = Db::name('user')->field('uid,money')->where('uid',$uid)->find();
        if($uidmoney['money'] < $data['money']) return [false,7001];   // 金额不足
        $topup = Db::name('topUp')->field('topid,money')->where(['uid'=>$uid,'bid'=>$data['bid']])->select();
        $umoney = 0;
        if($topup){
            foreach ($topup as &$val){
                $umoney += $val['money'];
            }
        }else{
            $umoney = 0;
        }
        $goodsOrder = Db::name('goodsOrder')->field('orderid,money,pay_type')
            ->where(['uid'=>$uid,'bid'=>$data['bid'],'pay_type'=>1,'status' => ['>',1]])
            ->select();
        $goodsmoney = 0;
        if($goodsOrder){
            foreach ($goodsOrder as &$va){
                $goodsmoney += $va['money'];
            }
        }else{
            $goodsmoney = 0;
        }
        $takes =  Db::name('takeOut')->field('takeid,money')->where(['uid'=>$uid,'bid'=>$data['bid'],'status'=>['>=',0]])->select();
        $takemoney = 0;
        if($takes){
            foreach ($takes as &$v){
                $takemoney += $v['money'];
            }
        }else{
            $takemoney = 0;
        }
        if(($umoney - $goodsmoney - $takemoney) == $uidmoney['money']){
            $data['status'] = 0;
            $data['createtime'] = time();
            $data['uid'] = $uid;
            Db::startTrans();
            $moneys = 0;
            $moneys = $uidmoney['money'] - $data['money'];
            $takeout = Db::name('takeOut')->insert($data);
            $usermo = Db::name('user')->update(['uid'=>$uid,'money'=>$moneys]);
            if (!$takeout || !$usermo) {
                Db::rollback(); //回滚事务
                return [false,0];
            }
            Db::commit();
            return [$data['money'],1];
        }else{
            return [false,0];
        }
    }

    

}
